package com.edgelight.controller;

import com.edgelight.dao.NewsRepository;
import com.edgelight.dao.SgCommentMapper;
import com.edgelight.pojo.SgComment;
import com.edgelight.pojo.resp.BaseResp;
import com.edgelight.service.NewsService;
import com.edgelight.service.SgCommentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/comment")
public class SgCommentController {
    @Resource
    private SgCommentService sgCommentService;

    @Autowired
    SgCommentMapper sgCommentMapper;

    @ApiOperation(value="插入根评论")
    @RequestMapping("/insertComment/{comment}")
    public BaseResp insertComment(@PathVariable("comment")String comment){
        BaseResp baseResp = sgCommentService.insertComment(comment);
        return baseResp;
    }


    @ApiOperation(value="查询根评论")
    @RequestMapping("/findIdAndArticleId/{page}/{size}/{articleId}")
    public BaseResp findIdAndArticleId(@PathVariable("page")Integer page, @PathVariable("size")Integer size,
                                       @PathVariable("articleId") Long articleId){
        BaseResp idAndArticleId = sgCommentService.findIdAndArticleId(page, size, articleId);

        //根评论
        List<SgComment> commentList =  sgCommentMapper.findIdAndArticleId(articleId);


        //查询根评论下面的子评论
        //commentList=评论list 所有的评论
        for (SgComment sgComment:commentList){
            //查询对应的子评论
            List<SgComment> children = getChildren(sgComment.getId());

            //赋值
            sgComment.setChildren(children);
        }

        PageHelper.startPage(page, size);
        PageInfo<SgComment> of = PageInfo.of(commentList);
        return new BaseResp(1,"ok",of.getList(),of.getTotal());



    }

    private List<SgComment> getChildren(Long id) {
        //根据根评论的id查询所对应子评论的集合
        List<SgComment> children = sgCommentMapper.findChildren(id);


        //取出对应这个评论id的所有子评论 root id不等于-1 且root id = id
        return children;

    }


}
